<template>
	<view class="details" :style="{paddingTop: paddingHeight + 'px'}">
		<nav-bar title="仪器管理"></nav-bar>
		<view class="device_card">
			<image :src="ble.state == 0 ? img_2 : img_1" class="device_mould" />
			<view class="s_c">
				<view class="d_name">
					<view class="name"
						:style="{color: ble.defaultInfo.name === deviceInfo.bluetoothName ? '#333333' : '#CCCCCC'}">
						{{ deviceInfo.bluetoothName ? deviceInfo.bluetoothName : ''}}
					</view>
					<u-image v-if="ble.defaultInfo.name === deviceInfo.bluetoothName" width="32rpx" height="32rpx"
						:showMenuByLongpress="false"
						src="http://oss.antaimedical.com/images/static/2024/07/66947d80eb14d0f049f44d556IGDqrK8xfZj335a584166aa26382d031e06222381c1.png"
						:lazy-load="true"></u-image>
					<u-image v-else width="32rpx" height="32rpx" :showMenuByLongpress="false"
						src="http://oss.antaimedical.com/images/static/2024/07/66947da0eb14d0f049f44d56N7Y0g57kb00R765831b67598dc25ba4a3728cd31b371.png"
						:lazy-load="true"></u-image>
				</view>
				<view class="d_i" v-if="ble.state === 0 && ble.defaultInfo.name === deviceInfo.bluetoothName">
					<text class="battery" v-if="ble.defaultInfo.battery">{{ ble.defaultInfo.battery }}%</text>
					<u-loading-icon v-else size="14" :show="true"></u-loading-icon>
					<u-image width="44rpx" height="26rpx" :showMenuByLongpress="false"
						:src="myGetBatteryIcon(ble.defaultInfo.battery)" :showLoading="false" :showError="false"
						:lazy-load="true"></u-image>
					<text class="line"></text>
					<text v-if="ble.defaultInfo.version">v{{ ble.defaultInfo.version }}</text>
					<u-loading-icon v-else size="14" :show="true"></u-loading-icon>
					<text class="line"></text>
					<text class="iconfont icon-lanya"></text>
				</view>
				<view class="connecting"
					v-else-if="ble.state === -2 && deviceInfo.bluetoothName === ble.BleConnectedName">
					<text class="l-t">连接中</text>
					<u-loading-icon size="18"></u-loading-icon>
				</view>
				<view class="connecting"
					v-else-if="ble.state === -3 && deviceInfo.bluetoothName === ble.BleConnectedName">
					<text class="l-t">连接中</text>
					<u-loading-icon size="18"></u-loading-icon>
				</view>
			</view>
		</view>
		<view class="cell" @click="$u.throttle(goInfo, 1000)">
			<text class="text">关于</text>
			<text class="iconfont icon-arrow_rigth"></text>
		</view>
		<view class="cell" @click="$u.throttle(checkBleStatus, 2000)"
			v-if="ble.defaultInfo.name !== deviceInfo.bluetoothName">
			<text class="text primary">重新连接</text>
			<text class="iconfont icon-arrow_rigth"></text>
		</view>
		<view class="cell" @click="showDelModal = true">
			<text class="text delete">删除仪器</text>
			<text class="iconfont icon-arrow_rigth"></text>
		</view>
		<u-modal :show="showDelModal" title="删除仪器" @close="showDelModal = false" @cancel="showDelModal = false"
			@confirm="$u.throttle(checkBle,2000)" confirmText="确定" cancelText="取消" showCancelButton
			cancelColor="#000000" confirmColor="#545DDE">
			<view class="tips">
				删除仪器,仪器将与当前账户解除绑定关系,确定继续?
			</view>
		</u-modal>
	</view>
</template>

<script>
	import {
		unbindDevice
	} from '@/api/index.js'
	import {
		mapState
	} from 'vuex'
	import {
		getBatteryIcon
	} from '@/utils/utils.js'
	const BLE = require('@/utils/ble.js');
	export default {
		data() {
			return {
				paddingHeight: uni.getStorageSync('navbarHeight'),
				userId: uni.getStorageSync('userId'),
				img_1: 'http://oss.antaimedical.com/images/static/2024/08/66b47bdbe4b09217821c0fa97zzIw6raL2Bxc2f498c39041f05b1284c3871aab3e21.png',
				img_2: 'http://oss.antaimedical.com/images/static/2024/08/66b47bc1e4b000d2c606b524bblrMJK2gq935a3581f5f3a72a294dcfd449f2b1e19c.png',
				deviceInfo: {}, // 仪器详情
				showDelModal: false, // 删除仪器确认框
				type: 'default' // 跳转类型
			}
		},
		computed: {
			...mapState({
				ble: state => state.ble, // 实时蓝牙全局状态
				userInfo: state => state.userInfo
			})
		},
		onLoad(OPTIONS) {
			this.deviceInfo = JSON.parse(OPTIONS.details)
			this.type = OPTIONS.type
		},
		methods: {
			// 连接仪器
			connect() {
				if (this.ble.state === -2) return
				// 判断当前是否连接仪器 并判断是否为当前页面仪器
				if (this.ble.state == 0 && this.ble.defaultInfo.name != this.deviceInfo.bluetoothName) {
					wx.closeBLEConnection({ // 断开
						deviceId: this.ble.devID,
						complete: () => {
							if (uni.$u.os() == 'android') { // 安卓系统直接连接
								this.$store.commit('setDefaultInfo', {
									type: 1,
									data: {
										mac: this.deviceInfo.deviceMac,
										name: this.deviceInfo.bluetoothName
									}
								})
								BLE.common.createBLEConnectionFn(this.deviceInfo.deviceMac, this
									.deviceInfo)
							} else { // 苹果系统需要搜索uuid仪器id
								BLE.common.myStartBluetoothDevicesDiscovery(10000, this.deviceInfo)
							}
						}
					})
				} else {
					if (uni.$u.os() == 'android') { // 安卓系统直接连接
						this.$store.commit('setDefaultInfo', {
							type: 1,
							data: {
								mac: this.deviceInfo.deviceMac,
								name: this.deviceInfo.bluetoothName
							}
						})
						BLE.common.createBLEConnectionFn(this.deviceInfo.deviceMac, this
							.deviceInfo)
					} else { // 苹果系统需要搜索uuid仪器id
						BLE.common.myStartBluetoothDevicesDiscovery(10000, this.deviceInfo)
					}
				}
				this.$store.commit('setBleConnectedName', this.deviceInfo.bluetoothName)
			},
			// 检查当前蓝牙状态
			checkBle() {
				if (this.ble.defaultInfo.name == this.deviceInfo.bluetoothName) {
					wx.closeBLEConnection({
						deviceId: this.ble.devID,
						complete: () => {
							this.unbind()
						}
					})
				} else {
					this.unbind()
				}
			},
			checkBleStatus() {
				let that = this
				if (this.ble.isOpenBleAdapter) {
					wx.getBluetoothAdapterState({
						success: res => {
							if (!res.available) {
								uni.showModal({
									title: '提示',
									content: '检测到手机蓝牙未打开,请前往手机[设置]-[蓝牙]打开蓝牙功能以扫描附近仪器',
									showCancel: false,
									confirmColor: '#545DDE'
								})
							} else {
								that.connect()
							}
						},
						fail: err => {
							uni.showModal({
								title: '提示',
								content: '请检查蓝牙功能是否正常',
								showCancel: false
							})
						}
					})
				} else {
					wx.closeBluetoothAdapter()
					wx.openBluetoothAdapter({
						success(BleObj) {
							that.$store.commit('changeIsOpenBleAdapter', true)
							that.connect()
						},
						fail(err) {
							console.log('openBluetoothAdapter', err)
							if (err.errCode == 10001) {
								that.$store.commit('changeIsOpenBleAdapter', true)
								uni.showModal({
									title: '提示',
									content: '检测到手机蓝牙未打开,请前往手机[设置]-[蓝牙]打开蓝牙功能以扫描附近仪器',
									showCancel: false,
									confirmColor: '#545DDE'
								})
							}
							if (err.errMsg == 'openBluetoothAdapter:fail auth deny') {
								uni.showModal({
									title: '提示',
									content: '请先授权蓝牙权限',
									confirmColor: '#545DDE',
									success(modal_res) {
										if (modal_res.confirm) {
											wx.openSetting({
												success: (authData) => {
													if (authData.authSetting[
															'scope.bluetooth']) {
														that.checkBleStatus()
													} else { // 未授权
														uni.showModal({
															title: '提示',
															content: '授权失败,您将无法使用蓝牙相关服务',
															confirmColor: '#545DDE',
															showCancel: false,
															success(modal) {
																if (modal
																	.confirm) {
																	wx.closeBluetoothAdapter()
																	that.$store.commit(
																		'changeIsOpenBleAdapter',
																		false)
																}
															}
														})

													}
												}
											})
										} else {
											uni.showModal({
												title: '提示',
												content: '授权失败,您将无法使用蓝牙相关服务',
												confirmColor: '#545DDE',
												showCancel: false,
												success(modal) {
													if (modal.confirm) {
														wx.closeBluetoothAdapter()
														that.$store.commit(
															'changeIsOpenBleAdapter',
															false)
													}
												}
											})
										}
									}
								})
							}
						}
					})
				}
			},
			async unbind() {
				uni.showLoading({
					title: '加载中...'
				})
				let params = {
					id: this.deviceInfo.id,
					userId: this.userId,
					urlencoded: true
				}
				try {
					const res = await unbindDevice(params)
					uni.hideLoading()
					if (res.code == 200) {
						this.showDelModal = false
						uni.showToast({
							title: '解绑成功'
						})
						setTimeout(() => {
							uni.$emit('refreshDevice')
							uni.navigateBack()
						}, 1200)
					}
				} catch (e) {
					//TODO handle the exception
					uni.hideLoading()
				}
			},
			myGetBatteryIcon(data) {
				return getBatteryIcon(data)
			},
			goInfo() {
				uni.navigateTo({
					url: `/pagesA/device/details/info?id=${this.deviceInfo.deviceId}`
				})
			}
		}
	}
</script>

<style lang="scss">
	page {
		background-color: #FAFAFA !important;
		min-height: 100%;
	}
</style>
<style lang="scss" scoped>
	.details {
		padding: 48rpx;

		.device_card {
			width: 100%;
			padding: 118rpx 0 48rpx;
			border-radius: 16rpx;
			background-color: #fff;
			margin: 48rpx 0 32rpx;
			display: flex;
			flex-direction: column;
			align-items: center;
			justify-content: center;


			.device_mould {
				width: 120rpx;
				height: 320rpx;
			}

			.s_c {
				margin-top: 48rpx;
				display: flex;
				flex-direction: column;
				align-items: center;

				.d_name {
					display: flex;
					align-items: center;

					.name {
						font-weight: 500;
						font-size: 36rpx;
						color: #333333;
						padding-right: 8rpx;
					}

					.icon-xiugai {
						color: #666666;
						font-size: 34rpx;
					}
				}

				.d_i {
					margin-top: 32rpx;
					display: flex;
					align-items: center;
					justify-content: center;
					font-size: 24rpx;
					color: #666;

					.battery {
						padding-right: 12rpx;
					}

					.line {
						width: 1rpx;
						height: 22rpx;
						background-color: rgba(#000, .1);
						margin: 0 16rpx;
					}

					.icon-lanya-F {
						color: #666666;
						font-size: 34rpx;
					}
				}

				.connecting {
					margin: 22rpx 0 0;
					display: flex;
					align-items: center;

					.l-t {
						font-size: 32rpx;
						color: #333333;
						padding-right: 10rpx;
					}
				}
			}
		}

		.cell {
			width: 100%;
			height: 118rpx;
			padding: 0 54rpx 0 48rpx;
			background: #FFFFFF;
			border-radius: 16rpx;
			margin-bottom: 16rpx;
			display: flex;
			align-items: center;
			justify-content: space-between;

			.text {
				font-size: 32rpx;
				color: #666666;
			}

			.primary {
				color: #545DDE;
			}

			.delete {
				color: #FA5151;
			}

			.icon-arrow_rigth {
				font-size: 34rpx;
				color: rgba(#666666, .5);
			}
		}

		.tips {
			padding: 0 54rpx 42rpx;
			color: #353535;
			font-size: 32rpx;
			text-align: center;
			letter-spacing: 1px;
		}
	}
</style>